import path from "node:path";
import UniApp from "@dcloudio/vite-plugin-uni";
import UniComponents from "@uni-helper/vite-plugin-uni-components";
import AutoImport from "unplugin-auto-import/vite";
import { defineConfig, loadEnv, ConfigEnv } from "vite";
import { NutResolver } from "nutui-uniapp";
import { UnifiedViteWeappTailwindcssPlugin as uvwt } from "weapp-tailwindcss/vite";
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";
import Components from "unplugin-vue-components/vite";
import { TDesignResolver } from "unplugin-vue-components/resolvers";

function r(...paths: string[]) {
  return path.resolve(process.cwd(), ".", ...paths);
}

const isH5 = process.env.UNI_PLATFORM === "h5";
const isApp = process.env.UNI_PLATFORM === "app";
const WeappTailwindcssDisabled = isH5 || isApp;

const resolve = (p) => {
  return path.resolve(__dirname, p);
};

export default defineConfig((mode: ConfigEnv) => {
  const env = loadEnv(mode.mode, process.cwd());
  return {
    resolve: {
      alias: {
        "@": r("src"),
      },
    },
    plugins: [
      UniComponents({
        resolvers: [NutResolver()],
      }),

      AutoImport({
        imports: [
          "vue",
          "pinia",
          "vue-router",
          {
            "nutui-uniapp/composables": [
              // 在这里添加需要自动导入的API
              "useToast",
            ],
          },
        ],
        dts: "auto-imports.d.ts",
      }),
      Components({
        resolvers: [TDesignResolver()],
        dts: "components.d.ts",
      }),
      (UniApp as any).default(),
      uvwt({
        rem2rpx: true,
        disabled: WeappTailwindcssDisabled,
        // 由于 hbuilderx 会改变 process.cwd 所以这里必须传入当前目录的绝对路径
        tailwindcssBasedir: __dirname,
      }),
    ],
    css: {
      postcss: {
        plugins: [tailwindcss(resolve("./tailwind.config.js")), autoprefixer as any],
      },
    },

    //
    server: {},
    //   // host: "0.0.0.0", // 服务器地址
    //   // port: 5173, // 服务器端口号
    //   open: true, // 是否自动打开浏览器
    //   hmr: true, // 启用热更新
    //   // proxy: {
    //   //   "/api": {
    //   //     target: env.VITE_ADMIN_PROXY_PATH, // 目标服务器地址
    //   //     ws: true, // 是否启用 WebSocket
    //   //     changeOrigin: true, // 是否修改请求头中的 Origin 字段
    //   //     rewrite: (path) => path.replace(/^\/api/, "/api"),
    //   //   },
    //   // },
    // },
  };
});
